package realestate.manager.owner;

import org.junit.AfterClass;
import org.junit.BeforeClass;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 20.04.11
 * Time: 10:47
 * To change this template use File | Settings | File Templates.
 */
public class OwnerCreator {

	protected static IRAOwner owner_manager;
	protected final static List<Owner> created_owners = new LinkedList<Owner>();

	@BeforeClass
	public static void init() throws NamingException {
		owner_manager = (IRAOwner) getObjectFromContext("OwnerManager/OwnerOwnerManager");
		addTestOwners();
	}

	public static Object getObjectFromContext(String name) {
		try {
			InitialContext ctx = new InitialContext();
			Object result = ctx.lookup("java:global/"+name);
			return result;
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return null;
	}


	private static void addTestOwners() {
		createOwner("testowner@test.i.com.tu.net");
		createOwner("testowner2@test.i.com.tu.net");
		createOwner("testowner3@test.i.com.tu.net");
	}

	private static void createOwner(String owner_e_mail) {
		Owner new_owner = new Owner();
		new_owner.setOwnerOwnerEMail(owner_e_mail);
		new_owner = owner_manager.addOwner(new_owner);
		created_owners.add(new_owner);
	}

	public static Owner getRandomOwner() {
		int random_index = getRandomInteger(created_owners.size());
		return created_owners.get(random_index);
	}

	public static int getRandomInteger(int range_count) {
		return (int) Math.round(Math.random()*(range_count-1));
	}

	@AfterClass
	public static void onFinish() {
		for(Owner registered_ownder: created_owners)
			owner_manager.removeOwner(registered_ownder);
	}


}
